import { useEffect, useState } from "react";
import { Form, Input, Button, message, Card } from "antd";
import { useUserInfo } from "@/store/userStore";
import { UploadBox } from "@/components/upload/upload-box";
import userService from "@/api/services/userService";

const AccountInfoTab = () => {
	const { username } = useUserInfo();
	const [form] = Form.useForm();
	const [loading, setLoading] = useState(false);

	useEffect(() => {
		const fetchUserInfo = async () => {
			try {
				const userInfo = await userService.getMyInfo();
				form.setFieldsValue({
					alipay_account: userInfo.alipay_account,
					alipay_account_name: userInfo.alipay_account_name,
					alipay_qr_code_img: userInfo.alipay_qr_code_img,
					wechat_qr_code_img: userInfo.wechat_qr_code_img,
				});
			} catch (error) {
				message.error("获取用户信息失败");
			}
		};
		fetchUserInfo();
	}, [form]);

	const onFinish = async (values: any) => {
		try {
			setLoading(true);
			await userService.updateMyInfo({
				...values,
			});
			message.success("保存成功");
		} catch (error) {
			message.error("保存失败");
		} finally {
			setLoading(false);
		}
	};

	return (
		<Card>
			<Form
				form={form}
				layout="vertical"
				onFinish={onFinish}
				initialValues={{
					username,
				}}
			>
				<Form.Item label="支付姓名" name="alipay_account_name">
					<Input placeholder="请输入支付宝账号" />
				</Form.Item>

				<Form.Item label="支付宝账号" name="alipay_account">
					<Input placeholder="请输入支付宝账号" />
				</Form.Item>

				<Form.Item label="支付宝收款码" name="alipay_qr_code_img">
					<UploadBox
						maxCount={1}
						accept="image/*"
					/>
				</Form.Item>

				<Form.Item label="微信收款码" name="wechat_qr_code_img">
					<UploadBox
						maxCount={1}
						accept="image/*"
					/>
				</Form.Item>

				<Form.Item>
					<Button type="primary" htmlType="submit" loading={loading} style={{ marginRight: 16 }}>
						保存
					</Button>
					<Button onClick={() => form.resetFields()}>重置</Button>
				</Form.Item>
			</Form>
		</Card>
	);
};

export default AccountInfoTab;
